/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-24 10:01:10
 * @LastEditors: LIFM0623 1944099171@qq.com
 * @LastEditTime: 2024-03-29 20:39:39
 * @FilePath: \scene_back_nest\src\cameraalong\cameraalong.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import {
  CreateCameraalongDto,
  RawCameraalongDto,
} from './dto/create-cameraalong.dto';
import { UpdateCameraalongDto } from './dto/update-cameraalong.dto';
import { Cameraalong } from './entities/cameraalong.entity';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class CameraalongService {

  constructor(
    @InjectRepository(Cameraalong)
    private readonly cameraalongRepository: Repository<Cameraalong>,
  ) {}
  async create(rawCameraalongDto: RawCameraalongDto) {
    const cameraalong = this.cameraalongRepository.create(rawCameraalongDto);
    const inserRes =  await this.cameraalongRepository.insert(cameraalong);
    return inserRes.raw;
  }

  async createForScript(rawCameraalongDto: RawCameraalongDto) {
    const cameraalong = this.cameraalongRepository.create(rawCameraalongDto);
    const inserRes =  await this.cameraalongRepository.insert(cameraalong);
    return inserRes.raw[0].id;
  }

  async findAll(): Promise<Cameraalong[]> {
    return this.cameraalongRepository.find();
  }

  async findByIds(ids: string[]): Promise<Cameraalong[]> {
    return this.cameraalongRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findOne(id: string): Promise<Cameraalong> {
    return this.cameraalongRepository.findOne({ where: { id: id } });
  }

  async update(id: string, updateCameraalongDto: UpdateCameraalongDto) {
    // 查找旧的用户实体
    const oldCameraalong = await this.cameraalongRepository.findOne({
      where: { id: id },
    });
    if (!oldCameraalong) {
      return '该相机跟随条目不存在';
    }
    const updatedCameraalong = this.cameraalongRepository.merge(
      oldCameraalong,
      updateCameraalongDto,
    );
    try {
      await this.cameraalongRepository.save(oldCameraalong);
      return '修改相机跟随条目属性成功!';
    } catch (err) {
      console.error('更新条目失败', err);
      throw '更新相机跟随条目失败';
    }
  }

  async remove(id: string) {
    try {
      const result = await this.cameraalongRepository.delete({ id: id });

      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
